/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.List;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.DataChangedListener;
import com.sun.lwuit.layouts.BorderLayout;
import core.IMAPMIDlet;
import core.RuntimeData;
import core.ScreenEngine;
import core.Settings;
import datamodel.Position;
import javax.microedition.lcdui.Canvas;
import network.Connection;
import network.PacketBuilder;
import view.additional.PositionListRenderer;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class PositionsForm extends BasicForm implements ActionListener, DataChangedListener
{
    private static final int STAND_COMMAND_ID = 1;
    
    private List items;
    private TextField filter;
    
    public PositionsForm()
    {
        super("to_position");
        
        init();
    }
    
    public void show()
    {
        filter.setText("");
        
        super.show();
    }
    
    private void init()
    {
        setLayout(new BorderLayout());
        setScrollable(false);
        
        filter = new TextField();
        filter.setSelectCommandText("");
        filter.setFocusable(Display.getInstance().isTouchScreenDevice());
        filter.setConstraint(TextArea.ANY);
        filter.setInputModeOrder(new String[]{"АБВ","абв","123"});

        filter.setUseSoftkeys(false);
        filter.addDataChangeListener(this);
        addComponent(BorderLayout.NORTH,filter);
        
        items = new List();
        items.setSelectCommandText("");
        items.setRenderer(new PositionListRenderer());
        items.setFixedSelection(List.FIXED_NONE_CYCLIC);
        items.addActionListener(this);
        addComponent(BorderLayout.CENTER, items);
        
        //Добавляем все стоянки
        setContent();
        
        //Команды на форме
        addCommand(new BackCommand());
        
        Command stand = new Command("stand", STAND_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                itemSelected((Position)items.getSelectedItem());
        
                evt.consume();
            }
        
        };
        addCommand(stand);
    }
    
    public void actionPerformed(ActionEvent evt)
    {
        itemSelected((Position)items.getSelectedItem());
        
        evt.consume();
    }
    
    private void itemSelected(Position selected)
    {
        if (selected == null)
        {
            return;
        }
        
        //Переежаем на стоянку
        RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        byte[] body = PacketBuilder.createBodyRegisterOnTaxiParking(selected.getId(), Settings.getSettings().getCallsign(), runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
        
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
    }
    
    private void clearItems()
    {
        synchronized(items)
        {
            while (items.size() > 0)
            {
                items.getModel().removeItem(0);
            }
        }
    }
    
    public void setContent() 
    {
        //Удаляем все предыдущее
        clearItems();
        
        //Заполняем список стоянок
        synchronized(items)
        {
            IMAPMIDlet.getMidlet().getPositionManager().fillPositionsListModel(items.getModel());
        }
    }
    
    public void dataChanged(int type, int index) 
    {
        String s = filter.getText();
        if (s.equals(""))
        {
            return;
        }
        
        synchronized(items)
        {
            for (int i = 0; i < items.size(); ++i)
            {
                if (((Position)items.getModel().getItemAt(i)).getParkingName().startsWith(s))
                {
                    items.setSelectedIndex(i);
                    break;
                }
            }
        }
    }
    
    public void keyReleased(int keyCode)
    {
        int game = Display.getInstance().getGameAction(keyCode);
        if(game == Display.GAME_DOWN || game == Display.GAME_UP) 
        {
            items.keyReleased(keyCode);
        }
        else if (keyCode == Canvas.KEY_NUM0 || keyCode == Canvas.KEY_NUM1 || keyCode == Canvas.KEY_NUM2 ||
                keyCode == Canvas.KEY_NUM3 || keyCode == Canvas.KEY_NUM4 || keyCode == Canvas.KEY_NUM5 ||
                keyCode == Canvas.KEY_NUM6 || keyCode == Canvas.KEY_NUM7 || keyCode == Canvas.KEY_NUM8 ||
                keyCode == Canvas.KEY_NUM9 || keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR)
        {
           filter.keyReleased(keyCode);
        }
        else
        {
            super.keyReleased(keyCode);
        }
    }
    
    public void keyPressed(int keyCode)
    {
        int game = Display.getInstance().getGameAction(keyCode);
        if(game == Display.GAME_DOWN || game == Display.GAME_UP) 
        {
            items.keyPressed(keyCode);
        }
        else if (keyCode == Canvas.KEY_NUM0 || keyCode == Canvas.KEY_NUM1 || keyCode == Canvas.KEY_NUM2 ||
                keyCode == Canvas.KEY_NUM3 || keyCode == Canvas.KEY_NUM4 || keyCode == Canvas.KEY_NUM5 ||
                keyCode == Canvas.KEY_NUM6 || keyCode == Canvas.KEY_NUM7 || keyCode == Canvas.KEY_NUM8 ||
                keyCode == Canvas.KEY_NUM9 || keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR)
        {
           filter.keyPressed(keyCode);
        }
        else if (game == Display.GAME_LEFT)
        {
            filter.deleteChar();
        }
        else
        {
            super.keyPressed(keyCode);
        }
    }
    
    public void keyRepeated(int keyCode)
    {
        int game = Display.getInstance().getGameAction(keyCode);
        if(game == Display.GAME_DOWN || game == Display.GAME_UP) 
        {
            items.keyRepeated(keyCode);
        }
        else if (keyCode == Canvas.KEY_NUM0 || keyCode == Canvas.KEY_NUM1 || keyCode == Canvas.KEY_NUM2 ||
                keyCode == Canvas.KEY_NUM3 || keyCode == Canvas.KEY_NUM4 || keyCode == Canvas.KEY_NUM5 ||
                keyCode == Canvas.KEY_NUM6 || keyCode == Canvas.KEY_NUM7 || keyCode == Canvas.KEY_NUM8 ||
                keyCode == Canvas.KEY_NUM9 || keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR)
        {
           filter.keyRepeated(keyCode);
        }
        else
        {
            super.keyRepeated(keyCode);
        }
    }
}
